<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>

<%
    String path = request.getContextPath();
    String ctx = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
    String wctx = request.getServerName()+":"+request.getServerPort()+path;
    String scheme=request.getScheme();
    String schemesocket=scheme=="https"?"wss":"ws";
%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script type="text/javascript" src="<%=ctx%>/websocket/jquery-1.12.3.min.js" ></script>
    <script type="text/javascript" src="<%=ctx%>/websocket/bootstrap.min.js" ></script>
    <link rel="stylesheet" href="<%=ctx%>/websocket/bootstrap.min.css" />
    <link href="<%=ctx%>/websocket/toastr.css" rel="stylesheet"/>
    <script type="text/javascript" src="<%=ctx%>/websocket/toastr.js"></script>
    <script type="text/javascript" src="<%=ctx%>/websocket/jquery.qqFace.js"></script>
      <style>
        body{
            margin-top:5px;background-color: #C0C0C0;overflow: hidden;
        }
        .container>row>col-md-3>panel>panel-heading{
            color: #fff;
            background-color: #273655;
            border-color: #273655;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-9">
            <div class="panel panel-primary">
                <div class="panel-heading" style="background-color: #273655;border-color: #273655;">
                    <h3 class="panel-title" id="talktitle">消息窗口</h3>
                </div>
                <div class="panel-body text-left">
                    <div class="well text-left" id="log-container" style="height:300px;overflow-y:scroll;margin-bottom:1px;">

                    </div>
                    <div class="text-left" style="width:100%;margin-bottom: 9px;margin-top: 5px;">
                        <button type="button" class="emotion btn btn-primary btn-xs">
                            <span class="glyphicon glyphicon-plus" style="font-size: 10px;margin-left: 5px;" title="表情包"></span> 表情
                        </button>
                    </div>
                    <%--<input type="text" id="myinfo" class="form-control col-md-12" />--%>
                    <textarea placeholder="消息内容"  id="myinfo" class="form-control col-md-12" rows="4" style="resize: none;font-family:Arial, Verdana, sans-serif;"></textarea><br>
                    <div class="container text-right float-right" style="width:100%;">
                        <div class="btn-group">
                            <button id="send" type="button" class="btn btn-default" style="right:20px;">发送</button>
                            <button id="broadcast" type="button" class="btn btn-default">群发</button>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3" style="height: 100%;position: absolute;right:1px;padding-right: 1px;">
            <div class="panel panel-primary" id="online" style="height: 100%;margin-bottom:0px;">
                <div class="panel-heading" style="background-color: #273655;border-color: #273655;">
                    <h3 class="panel-title">在线用户</h3>
                </div>
                <div class="panel-body" style="margin-bottom:0px;">
                    <div class="list-group" id="users">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    $(document).ready(function() {
        // 指定websocket路径
        var websocket;
        if ('MozWebSocket' in window) {
            websocket = new MozWebSocket("<%=schemesocket%>://<%=wctx%>/ws?username=${sessionScope.username}");
        } else if ('WebSocket' in window) {
            websocket = new WebSocket("<%=schemesocket%>://<%=wctx%>/ws?username=${sessionScope.username}");
        } else {
            websocket = new SockJS("<%=schemesocket%>://<%=wctx%>/ws?username=${sessionScope.username}");
        }
        //var websocket = new WebSocket('ws://localhost:8080/Spring-websocket/ws');
        websocket.onmessage = function(event) {
            var rdata=event.data;
            console.log("======================"+typeof(rdata)+"====================");
            console.log(rdata);

            if(typeof(rdata)=="string" ){
                var data=JSON.parse(rdata);
                if("${sessionScope.username}"==data.fromName){
                    return;
                }
                if(data.from==0){//上线消息
                    if(data.text!="${sessionScope.username}")
                    {
                        //$("#users").append('<a href="#" onclick="talk(this)" class="list-group-item">'+data.text+'</a>');
                        $("#users").append('<a href="#" onclick="talk(this)" class="list-group-item"><img src="<%=ctx%>/websocket/image/touxiang.png" width="32">&nbsp;<span>'+data.text+'</span>&nbsp;在线</a>');
                        //alert(data.text+"上线了");
                        toastr.info(data.text+"上线了");
                    }
                }else if(data.from==-2){//下线消息
                    if(data.text!="${sessionScope.username}")
                    {
                        $("#users > a").remove(":contains('"+data.text+"')");
                        //alert(data.text+"下线了");
                        toastr.info(data.text+"下线了");
                    }
                }else{//用户或者群消息
                    // 接收服务端的实时消息并添加到HTML页面中
                    toastr.info(data.fromName+":"+data.text.substring(0,15)+"...");
                    $("#log-container").append("<div class='bg-info'><label class='text-danger'>"+data.fromName+"&nbsp;"+data.date+"</label><div class='text-success'>"+data.text+"</div></div><br>");
                    // 滚动条滚动到最低部
                    scrollToBottom();
                }
            }
        };

        setTimeout(function () {
            $.post("onlineusers",function(data){
                for(var i=0;i<data.length;i++)
                    $("#users").append('<a href="#" onclick="talk(this)" class="list-group-item"><img src="<%=ctx%>/websocket/image/touxiang.png" width="32">&nbsp;<span>'+data[i]+'</span>&nbsp;在线</a>');
            });
            $('.emotion').qqFace({
                id: 'facebox',
                assign: 'myinfo',
                path: '<%=ctx%>/websocket/arclist/'	//表情存放的路径
            });
        }, 2000);
        $("#broadcast").click(function(){
            var v=$("#myinfo").val();
            if(v=="") {
                return;
            }
            v=replace_em(v);
            //$.post("broadcast",{"text":$("#myinfo").val()});
            //$("#myinfo").val("");
            var data={};
            data["from"]=1;
            data["fromName"]="${sessionScope.username}";
            data["to"]=-1;
            data["toName"]="";
            data["text"]=v;
            websocket.send(JSON.stringify(data));
            $("#log-container").append("<div class='bg-success'><label class='text-info'>我&nbsp;"+formatDateTime(new Date())+"</label><div class='text-info'>"+v+"</div></div><br>");
            //scrollToBottom();
            $("#myinfo").val("");
        });

        $("#send").click(function(){
                var toName=$("body").data("to");
                var v=$("#myinfo").val();

                if(v==""){
                    return;
                }else{
                    v=replace_em(v);
                    var data={};
                    data["from"]=1;
                    data["fromName"]="${sessionScope.username}";
                    data["to"]=-1;
                    data["toName"]=toName;
                    data["text"]=v;
                    websocket.send(JSON.stringify(data));
                    $("#log-container").append("<div class='bg-success'><label class='text-info'>我&nbsp;"+formatDateTime(new Date())+"</label><div class='text-info'>"+v+"</div></div><br>");
                    scrollToBottom();
                    $("#myinfo").val("");
                }
            });
    });

    function talk(a){
        var chooseonlineuser=a.getElementsByTagName("span")[0].innerHTML;
        $("#talktitle").text("与"+chooseonlineuser+"的聊天");
        $("body").data("to",chooseonlineuser);
    }
    function scrollToBottom(){
        var div = document.getElementById('log-container');
        div.scrollTop = div.scrollHeight;
    }
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "newestOnTop": false,
        "progressBar": false,
        "positionClass": "toast-bottom-right",
        "preventDuplicates": false,
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    }
    var formatDateTime = function (date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h=h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        var second=date.getSeconds();
        second=second < 10 ? ('0' + second) : second;
        return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
    };
    window.onkeydown = function (ev) {
        var key = ev.keyCode;    //获取对应键盘的ascii码

        if (key == 13) {
            $("#send").click();
        }
    }
    function replace_em(str) {
        str = str.replace(/\</g, '&lt;');
        str = str.replace(/\>/g, '&gt;');
        str = str.replace(/\n/g, '<br/>');
        str = str.replace(/\[em_([0-9]*)\]/g, '<img src="<%=ctx%>/websocket/arclist/$1.gif" border="0" />');
        return str;
    }
</script>
</body>
</html>
